﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Web.Utility;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using System.Web.UI.HtmlControls;
using BySoft.Server.Business.UserCode;

namespace BySoft.Web.Site.StockManage
{
    public partial class ReturnMatAdd : AuthBasePage
    {
        #region 属性定义
        private string m_strTbl = "BS_ReturnMat" + DateTime.Now.ToString("yyMMdd");
        private string m_strMainKey = "BillID";
        private static DataTable dtStock = null;
        private DataTable DtReturnMatData
        {
            get
            {
                if (null == Session["DtReturnMatData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["DtReturnMatData"];
                }
            }
            set
            {
                Session["DtReturnMatData"] = value;
            }
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BillDetailID");//0
            dt.Columns.Add("MatUseDetailID");//1 
            dt.Columns.Add("MaterialID");//2 
            dt.Columns.Add("MaterialName");//4
            dt.Columns.Add("Specifications");//7
            dt.Columns.Add("Unit");//8
            dt.Columns.Add("ChangeNum");//5 
            dt.Columns.Add("UseNums");//9
            dt.Columns.Add("LeftNums");//10
            dt.Columns.Add("StockNums");//11
            dt.Columns.Add("Nums");//12 
            dt.Columns.Add("MMNumber");//12 
            dt.Columns.Add("SingleMMNumber");//12 
            dt.Columns.Add("Remark");//13 
            dt.Columns.Add("IsNew");//14 
            dt.Columns.Add("IsDel");//14
            return dt;
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            txtWorkOrderNo.Attributes.Add("readonly", "true");
            txtScheduleID.Attributes.Add("readonly", "true");
            txtProductID.Attributes.Add("readonly", "true");
            txtProductName.Attributes.Add("readonly", "true");
            txtProductNum.Attributes.Add("readonly", "true");
            DtReturnMatData = null;
            SetControlAttr(new BsReturnmatEntity(), tBase);
            lblBillID.Text = ClsComm.GetMaxSequenceID(m_strTbl, "RM" + DateTime.Now.ToString("yyMMdd"), 3);
            cpBillDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
            UIHelper.BindEmptyGridView(grdResult, CreateDT());
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

        private void AddPro()
        {
            DtReturnMatData = GetAddPro(DtReturnMatData).Copy();
        }
        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblBillDetailID = gvr.FindControl("lblBillDetailID") as Label;
                Label lblMatUseDetailID = gvr.FindControl("lblMatUseDetailID") as Label;
                Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                Label lblUnit = gvr.FindControl("lblUnit") as Label;
                Label lblChangeNum = gvr.FindControl("lblChangeNum") as Label;
                Label lblUseNums = gvr.FindControl("lblUseNums") as Label;
                Label lblLeftNums = gvr.FindControl("lblLeftNums") as Label;
                Label lblStockNums = gvr.FindControl("lblStockNums") as Label;
                TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
                Label lblSingleMMNumber = gvr.FindControl("lblSingleMMNumber") as Label;
                TextBox txtMMNumber = gvr.FindControl("txtMMNumber") as TextBox;
                TextBox txtRemark = gvr.FindControl("txtRemark") as TextBox;

                string MatUseDetailID = CommonMethod.GetString(lblMatUseDetailID.Text);


                DataRow[] drs = dtTemp.Select("MatUseDetailID='" + MatUseDetailID + "'");
                if (drs.Length > 0)
                {

                    drs[0]["BillDetailID"] = GetGridViewString(lblBillDetailID);
                    drs[0]["MatUseDetailID"] = GetGridViewString(lblMatUseDetailID);
                    drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                    drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                    drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                    drs[0]["Unit"] = GetGridViewString(lblUnit);
                    drs[0]["ChangeNum"] = GetGridViewString(lblChangeNum);
                    drs[0]["UseNums"] = GetGridViewString(lblUseNums);
                    drs[0]["LeftNums"] = GetGridViewString(lblLeftNums);
                    drs[0]["StockNums"] = GetGridViewString(lblStockNums);
                    drs[0]["Nums"] = GetGridViewString(txtNums);
                    drs[0]["SingleMMNumber"] = GetGridViewString(lblSingleMMNumber);
                    drs[0]["MMNumber"] = GetGridViewString(txtMMNumber);
                    drs[0]["Remark"] = GetGridViewString(txtRemark);
                }
            }
            return dtTemp;
        }

        private void BindData()
        {
            DataView dv = new DataView(DtReturnMatData);
            dv.RowFilter = "IsDel<>'1'";
            dv.Sort = " MatUseDetailID ";
            DataTable dtTemp = dv.ToTable();
            if (dtTemp.Rows.Count > 0)
            {
                grdResult.DataSource = dtTemp;
                grdResult.DataBind();
                SetControlAttr(new BsPurchasedetailEntity(), grdResult);
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, CreateDT());
            }
            UIHelper.RunScript(this.UpdatePanel1, "iframeAutoFit();");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            AddPro();
            string strScheduleDetailID = hdScheduleDetailID.Value.Trim();
            UIHelper.RunScript(this.Page, "importNewRow('" + strScheduleDetailID + "');");
        }

        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            BsReturnmatEntity entity = new BsReturnmatEntity();
            entity.BillID = GetString(lblBillID);
            entity.BillDate = GetDateTime(cpBillDate);
            entity.ScheduleDetailID = GetDecimal(hdScheduleDetailID);
            entity.WorkOrderNo = GetString(txtWorkOrderNo);
            entity.Status = "1";
            entity.CreateUserID = CurrentUser.UserID;
            entity.CreateUserName = CurrentUser.UserName;
            entity.CreateDate = DateTime.Now;
            entity.ModifyUserID = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;


            BsReturnMatBusiness.SaveOrUpdate(entity, DtReturnMatData, "Save");
            ClsComm.SetMaxSequenceID(m_strTbl);
            base.LogAction(BaseEnum.ActionType.Add, entity.BillID, true, null, new EntityBase[] { entity });
            DtReturnMatData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../StockManage/ReturnMatList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
                AddPro();
                DataTable dt = DtReturnMatData.Copy();

                DataRow[] drs = dt.Select("MatUseDetailID='" + str + "'  and IsDel<>'1' ");
                if (drs != null && drs.Length > 0)
                {
                    drs[0]["IsDel"] = "1";
                }
                DtReturnMatData = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion
            }
        }
        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            string strMention = "";
            AddPro();

            DataView dv = new DataView(DtReturnMatData);
            dv.RowFilter = "IsDel<>'1'";
            dv.Sort = " MaterialID ";
            DataTable dtTemp = dv.ToTable();
            if (dtTemp.Rows.Count < 1)
            {
                UIHelper.AlertMessage(this.Page, "请添加明细！");
                return false;
            }

            string strOriMainKey = UIHelper.GetQueryStringValue("id").Trim();
            if (!string.IsNullOrEmpty(strOriMainKey))
            {
                if (lblBillID.Text != strOriMainKey)
                {
                    if (ClsComm.CheckExist("BS_ReturnMat", "BillID", lblBillID.Text.Trim(), true))
                    {
                        strMention = "材料领用单编号已经存在！<br />";
                    }
                }
            }
            else
            {
                if (ClsComm.CheckExist("BS_ReturnMat", "BillID", lblBillID.Text.Trim(), true))
                {
                    strMention = "材料领用单编号已经存在！<br />";
                }
            }
            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                ClsComm.SetMaxSequenceID(m_strTbl);
                return false;
            }
        }
        #endregion
    }
}
